<template>
  <div class="add-goods">
    <el-col :span="24" class="action-bar">
      <el-button @click="$router.back(-1)" type="primary" size="medium" style="margin-left:20px;">返回</el-button>
    </el-col>

    <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">

      <div class="step">
        <h1 id="baseMessage">基础信息</h1>

        <el-form-item label="UPC码" prop="upc">
          <el-col :span="24">
            <el-autocomplete
              style="width: 350px"
              class="inline-input"
              v-model="upcMatchForm"
              :fetch-suggestions="querySearch"
              placeholder="请输入UPC码"
              :trigger-on-focus="false"
              @select="handleSelect"
              @change="upcChange()"
            ></el-autocomplete>
            <span style="color: grey;margin-left: 10px" v-if="upcMatchFlag&&upcFistGetFlag">很抱歉，暂时没有匹配的商品信息</span>
            <!--<el-input v-model="addForm.upc"placeholder="请输入UPC码，将自动从药品库中匹配药品信息"></el-input>-->
          </el-col>
        </el-form-item>


        <el-form-item label="门店" prop="merchant_id">
          <el-select :disabled="formStoreOne" v-model="addForm.merchant_id" @change="chooseMerchantByAdd(addForm.merchant_id)" placeholder="选择门店">
            <el-option v-for="opt in merchantList" :key="opt.id" :value="opt.id" :label="opt.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-select v-model="addForm.classify_first_id" placeholder="选择分类"  @change="chooseClassifyByAdd('first')">
            <el-option v-for="opt in classifyList" :key="opt.id" :value="opt.id" :label="opt.name" />
          </el-select>

          <el-select style="margin-left: 8px" v-if="classifyListSecond.length>0" v-model="addForm.classify_second_id" placeholder="选择二级分类"  @change="chooseClassifyByAdd('second')">
            <el-option v-for="opt in classifyListSecond" :key="opt.id" :value="opt.id" :label="opt.name" />
          </el-select>
          <span style="color: grey;margin-left: 10px" v-if="!addForm.merchant_id">请选择门店</span>
        </el-form-item>

<!--        <el-form-item label="药品类型" v-if="!upcMatchFlag&&upcFistGetFlag">-->
<!--          <el-select v-model="addForm.type_id" placeholder="" disabled="disabled">-->
<!--            <el-option :value="0" :label="'OTC非处方药'" />-->
<!--            <el-option :value="1" :label="'Rx处方药'" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="商品图片" style="color: black;">
          <image-drag
            :picList="picList"
            :multiple="true"
            :action="()=> {return this.$api.UPLOAD_IMG}"
            :on-error="uploadError"
            :on-success="handleSuccess"
            @update="updateFile">
          </image-drag>
        </el-form-item>

        <el-form-item label="商品名称" prop="name">
          <el-col :span="8">
            <el-input v-model="addForm.name"placeholder="请输入商品名称"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="商品编码" prop="code" >
          <el-col :span="8">
            <el-input v-model="addForm.ssn" placeholder="请输入商品编码"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="展示状态" >
          <span>下架</span>
          <el-switch
            style="margin: 0 10px"
            v-model="isShop"
            active-color="#13ce66"
            inactive-color="#ff4949" @change="switchChange"></el-switch>
          <span>上架</span>
        </el-form-item>

        <el-form-item label="价格" >
          <el-col :span="8">
            <el-input type="number" :min="0" v-model="addForm.selling_price" placeholder="价格" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="库存":min="0" >
          <el-col :span="8">
            <el-input type="number" v-model="addForm.stock" placeholder="库存" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="排序" >
          <el-col :span="8">
            <el-input type="number" v-model="addForm.sort" placeholder="排序"></el-input>
          </el-col>
        </el-form-item>
      </div>
      <div class="divider" v-if="skuList.length>0"></div>
      <div v-if="!upcMatchFlag&&upcFistGetFlag&&skuList.length>0" class="step">
        <h1>销售信息</h1>
        <el-form-item label="规格">
          <el-button type="primary" @click="showAddSkuDialog">添加属性</el-button>
        </el-form-item>
        <!--列表-->
        <!--<el-table :data="skuTableData" class="el-table-style">
          <el-table-column
            v-for="col in specNameArr"
            :prop="col" :label="col" >
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="100" sortable></el-table-column>
        </el-table>-->
        <table class="gridtable" v-if="skuTableData.length>0">
          <tr>
            <th v-for="(item,index) in specNameArr" :key="index">{{item.name}}</th>
            <th>图片</th>
            <th>售价/元</th>
            <th>库存</th>
            <th>规格编码</th>
          </tr>
          <tr v-for="(item,index) in skuTableData" :key="index">
            <td v-for="(sku,skuIndex) in item.skuArr" :key="skuIndex">{{sku.name}}</td>
            <td>
              <el-upload class="avatar-uploader" :action="$api.UPLOAD_IMG" name='photo'
                         :show-file-list="false" :on-success="function (res, file) { return skuUploadSuccess(res, file, index)}" :before-upload="beforeSkuAvatarUpload(index)">
                <img v-if="item.other.thumb_url" :src="item.other.thumb_url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </td>
            <td><el-input type="number" v-model="item.other.price" /></td>
            <td><el-input type="number" v-model="item.other.stock"/></td>
            <td><el-input type="text" v-model="item.other.code"/></td>
          </tr>
        </table>
      </div>
      <div class="divider"></div>
      <div class="step">
        <h1>促销活动</h1>
        <el-form-item label="促销规则">
          <el-select multiple v-model="addForm.discount_sales_rule" placeholder="选择促销规则">
            <el-option v-for="opt in discountSalesRuleList" :key="opt.id" :value="opt.id" :label="opt.name" />
          </el-select>
        </el-form-item>
      </div>
<!--      <div class="divider"></div>-->
<!--      <div class="step">-->
<!--        <h1>参数信息</h1>-->
<!--        <div style="display: flex">-->
<!--          <div style="flex: 1">-->
<!--            <el-form-item label="生产厂商">-->
<!--              <el-col :span="20">-->
<!--                <el-input  :disabled="!upcMatchFlag" v-model="addForm.manufacturer" :placeholder="upcMatchFlag?'生产厂商':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="规格">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.specification" :placeholder="upcMatchFlag?'规格':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="用量方法">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.usage_and_dosage" :placeholder="upcMatchFlag?'用量方法':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="适应人群">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.adapt_to_the_crowd" :placeholder="upcMatchFlag?'适应人群':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="不良反应">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.adverse_reactions" :placeholder="upcMatchFlag?'不良反应':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="注意事项">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.precautions" :placeholder="upcMatchFlag?'注意事项':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="儿童用药">-->
<!--              <el-col :span="20">-->
<!--                <el-input :disabled="!upcMatchFlag" v-model="addForm.medication_for_children" :placeholder="upcMatchFlag?'儿童用药':''"></el-input>-->
<!--              </el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="老年人用药">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.medication_for_aged" :placeholder="upcMatchFlag?'老年人用药':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="包装" >-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.packing" :placeholder="upcMatchFlag?'包装':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="贮藏" >-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.storage" :placeholder="upcMatchFlag?'贮藏':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="有效期" >-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.expiry_date" :placeholder="upcMatchFlag?'有效期':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--          </div>-->

<!--          <div style="flex: 1;margin-right: 10px">-->
<!--            <el-form-item label="批准文号">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.approval_number" :placeholder="upcMatchFlag?'批准文号':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="电子监管码">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.electronic_regulatory_code" :placeholder="upcMatchFlag?'电子监管码':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="适应症">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.indications" :placeholder="upcMatchFlag?'适应症':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="成分">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.component" :placeholder="upcMatchFlag?'成分':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="禁忌">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.contraindications" :placeholder="upcMatchFlag?'禁忌':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="药物相互作用">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.interaction" :placeholder="upcMatchFlag?'药物相互作用':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="妊娠与哺乳用药">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.medication_for_pregnancy_x_lactation" :placeholder="upcMatchFlag?'妊娠与哺乳用药':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="性质">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.properties" :placeholder="upcMatchFlag?'性质':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="剂型">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.dosage_form" :placeholder="upcMatchFlag?'剂型':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="药理作用">-->
<!--              <el-col :span="20"><el-input :disabled="!upcMatchFlag" v-model="addForm.pharmacological_action" :placeholder="upcMatchFlag?'药理作用':''"></el-input></el-col>-->
<!--            </el-form-item>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
      <div class="divider"></div>
      <div class="step">
        <h1>商品详情</h1>
        <div style="padding: 0 20px">
          <vue-ueditor-wrap v-model="addForm.detail" :config="myConfig"></vue-ueditor-wrap>
        </div>
      </div>
      <div class="divider"></div>

      <div style="padding: 20px 0 10px 20px">
        <el-button type="primary" @click="addSubmitBtn()">{{upcMatchFlag?'提交审核':'添加'}}</el-button>
        <el-button @click="$router.back(-1)" size="medium" style="margin-left:20px;">返回</el-button>
      </div>

      <!-- 添加规格信息 -->
      <el-dialog title="添加属性" :visible.sync="addSpuVisible" width="50%">
        <el-form label-width="100px">
          <el-form-item label="选择属性名称">
            <el-select disabled multiple v-model="specArr" @change="chooseSpec()" placeholder="选择属性名称">
              <el-option v-for="opt in skuList" :key="opt.id" :value="opt.id" :label="opt.name" />
            </el-select>
          </el-form-item>
          <div class="spec-item" v-for="(item,index) in specValueArr" :key="index">
            <h1 style="font-size: 15px;padding-bottom: 10px">{{item.name}}</h1>
            <el-checkbox-group v-model="specValueArrAAAA[index]">
              <el-checkbox v-for="(opt,cbIndex) in item.value_list" :key="opt.id" :label="opt.id">{{opt.value}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <!--<div class="spec-item" v-for="(item,index) in specArr" :key="index">
            <h1 style="font-size: 15px;padding-bottom: 10px">{{specValueArr[index].name}}</h1>
            <el-checkbox-group v-model="specValueArrAAAA[index]">
              <el-checkbox v-for="(opt,cbIndex) in specValueArr[index].value_list" :key="opt.id" :label="opt.id">{{opt.value}}</el-checkbox>
            </el-checkbox-group>
          </div>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="addSpuVisible = false">取消</el-button>
          <el-button type="primary" @click="addSkuBtn">添加</el-button>
        </div>
      </el-dialog>

    </el-form>
  </div>
</template>

<script>
    import imageDrag from "./compoents/image-drag"
    export default {
      name: "add_goods",
      components: {
        'image-drag': imageDrag
      },
      data() {
        return {
          upcMatchForm: '',
          goodsListPage: '',
          isShop: true,
          discountSalesRuleList: [],//促销规则
          dialogImageUrl: '',
          dialogVisible: false,
          picList: [],
          fileList: [],//显示图片格式[{url: 'https://yaogeeks.dindong.cn/api/file/show-image/54'}]
          headerFixed: false,//吸顶标志
          offsetTop: '',
          offsetLeft: '',
          addForm: {
            type_id: '',//药品类型
            rules: '',
            upc: '',
            name: '',
            imageUrl: '',
            classify_first_id: '',
            classify_second_id: '',
            classify_id: '',
            classify_name: '',
            merchant_name: '',
            merchant_id: '',
            ssn: '',
            sku_ssn: '',//内部库存编号
            approval_number: '',//批准文号
            specification: '',//规格
            thumb_id: [],//商品封面图ID
            selling_price: '',//销售价格
            stock: '',//库存
            manufacturer: '',//生产厂商名称
            manufacturer_address: '',//生产厂商地址
            manufacturer_contact: '',//生产厂商联系方式
            electronic_regulatory_code: '',//电子监管码
            usage_and_dosage: '',//用法用量
            indications: '',//适应症
            adapt_to_the_crowd: '',//适应人群
            component: '',//成分
            adverse_reactions: '',//不良反应
            contraindications: '',//禁忌
            precautions: '',//注意事项
            interaction: '',//药物相互作用
            medication_for_children: '',//儿童用药
            medication_for_pregnancy_x_lactation: '',//妊娠与哺乳用药
            medication_for_aged: '',//老年人用药
            properties: '',//性状
            packing: '',//包装
            dosage_form: '',//剂型
            storage: '',//贮藏
            pharmacological_action: '',//药理作用
            expiry_date: '',//有效期
            detail: '',
            is_shop: 1,//是否上架，0：否 1：是
            sort: '',
            discount_sales_rule: ''
          },
          classifyList: [],
          sortVal:undefined,
          classifyListSecond: [],
          merchantList: [],
          upcMatchFlag: true,
          upcFistGetFlag: false,
          ruleForm: {
            name: '',
            region: '',
            date1: '',
            date2: '',
            delivery: false,
            type: [],
            resource: '',
            desc: ''
          },
          upcList: [],
          restaurants: [],
          rules: {
            upc: [
              { required: true, message: '请输入UPC码', trigger: 'change' }
            ],
            merchant_id: [
              { required: true, message: '请选择门店', trigger: 'change' }
            ],
            name: [
              { required: true, message: '请输入商品名称', trigger: 'blur' }
            ]
          },
          addSpuVisible: false,
          skuValueArr: [],
          skuInfoArr: [],
          specArr: [],
          specArrTemp: [],
          specValueArr: [],
          specValueArrAAAA: [],
          skuList: [],
          skuTableData: [],
          specNameArr: [],
          formStoreOne: false,
          myConfig: {
            // 编辑器不自动被内容撑高
            autoHeightEnabled: false,
            // 初始容器高度
            initialFrameHeight: 500,
            // 初始容器宽度
            initialFrameWidth: '100%',
            serverUrl: this.$api.ueditorUrl,
            // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
            UEDITOR_HOME_URL: '/UEditor/',
            toolbars: [
              [
                'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'strikethrough',
                'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
                'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'simpleupload', 'insertvideo', 'music',
                'horizontal', 'date', 'time',
                'inserttable'
              ]
            ]
          },
        };
      },
      watch: {
        'upcMatchForm'(newVal, oldVal) {
          this.addForm.upc = newVal
          this.getUPCList()
        }
      },
      mounted() {
          this.goodsListPage = this.$route.query.goodsListPage
          if(this.$route.query.merchant_id){
            this.addForm.merchant_id = parseInt(this.$route.query.merchant_id)
            this.formStoreOne = true
            this.getGoodsClassifyList(this.addForm.merchant_id)
          } else{
            this.formStoreOne = false
          }
          this.getMerchantList();
          this.getGoodsSkuList();
          this.getDiscountSalesRule();
          /*this.getUPCList();*/
      },
      methods: {

        //展示状态发生变化
        switchChange(e) {
          if(this.isShop){
            this.addForm.is_shop = 1
          } else{
            this.addForm.is_shop = 0
          }
        },

        //获取门店列表
        async getMerchantList(){
          this.page = this.page
          let params = {
            limit:99,
            page:1
          }
          const res = await this.$api.getMerchantList(params);
          if(res.data.level=='success'){
            let list = res.data.data;
            this.merchantList = list;
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        //获取所有的upc码
        async getUPCList() {
          let params = {
            limit:10,
            page:1,
            upc: this.upcMatchForm
          }
          const res = await this.$api.getSystemMedicineUpcList(params);
          if(res.data.level=='success'){
            this.upcList = []
            this.restaurants = []
            let list = res.data.data;
            list.forEach((item,index) => {
              let tempObj = {}
              tempObj.value = item
              this.upcList.push(tempObj)
            })
            this.restaurants = this.upcList

          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        createFilter(queryString) {
          return (restaurant) => {
            return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        },

        querySearch(queryString, cb) {
          let restaurants = this.restaurants;
          let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
        },

        handleSelect(item) {
          console.log(item);
          this.upcMatchFlag = false
          this.getSystemMedicineByUpc(item.value)
        },

        async getSystemMedicineByUpc(upc) {
          this.upcMatchFlag = false
          this.upcFistGetFlag = true;
          const res = await this.$api.getSystemMedicineByUpc({upc: upc});
          if(res.data.level=='success'){
            this.upcMatchFlag = false
            let data = res.data.data;
            /*this.addForm.id = data.id;*/
            /*this.addForm.upc = data.upc;*/
            this.addForm.name = data.name;
            /*this.addForm.ssn = data.ssn;*/
            /*this.addForm.imageUrl = data.imageUrl;*/
            /*this.addForm.merchant_id = parseInt(data.merchant_id);*/
            /*let str = [];
            if(data.first_classify_id){
              this.addForm.classify_first_id = parseInt(data.first_classify_id);
              str.push(parseInt(data.first_classify_id));
            } else{
              this.addForm.classify_first_id = '';
            }
            if(data.second_classify_id){
              this.addForm.classify_second_id = parseInt(data.second_classify_id);
              str.push(parseInt(data.second_classify_id));// TODO TODO TODO
              this.getGoodsClassifyList(this.addForm.merchant_id,this.addForm.classify_first_id)
            } else {
              this.addForm.classify_second_id = '';
              this.classifyListSecond = []
            }
            this.addForm.classify_id = str;*/

            this.addForm.sku_ssn = data.sku_ssn;//内部库存编号
            this.addForm.approval_number = data.approval_number;//批准文号
            this.addForm.specification = data.specification;//规格

            this.addForm.thumb_id = []
            this.fileList = []
            this.picList = []
            if(data.thumb_url&&data.thumb_url.length>0){
              data.thumb_url.forEach((item,index) => {
                let obj = {}
                obj.id = item.img_id
                obj.key = item.img_id
                obj.url = item.img_Url
                this.addForm.thumb_id.push(item.img_id)
                this.picList.push(obj)
              })
            }

            /*this.addForm.thumb_id = data.thumb_id;//商品封面图ID
            this.addForm.thumb_url = data.thumb_url;//商品封面图ID*/

            /*this.addForm.is_shop = data.is_shop
            if(this.addForm.is_shop == 1){
              this.isShop = true;
            } else{
              this.isShop = false;
            }*/
            this.addForm.type_id = parseInt(data.drug_type)
            this.addForm.selling_price = data.selling_price;//销售价格
            this.addForm.stock = data.stock;//库存
            this.addForm.manufacturer = data.manufacturer;//生产厂商名称
            this.addForm.manufacturer_address = data.manufacturer_address;//生产厂商地址
            this.addForm.manufacturer_contact = data.manufacturer_contact;//生产厂商联系方式
            this.addForm.electronic_regulatory_code = data.electronic_regulatory_code;//电子监管码
            this.addForm.usage_and_dosage = data.usage_and_dosage;//用法用量
            this.addForm.indications = data.indications;//适应症
            this.addForm.adapt_to_the_crowd = data.adapt_to_the_crowd;//适应人群
            this.addForm.precautions = data.precautions;//注意事项
            this.addForm.component = data.component;//成分
            this.addForm.adverse_reactions = data.adverse_reactions;//不良反应
            this.addForm.contraindications = data.contraindications;//禁忌
            this.addForm.recautions = data.recautions;//注意事项
            this.addForm.interaction = data.interaction;//药物相互作用
            this.addForm.medication_for_children = data.medication_for_children;//儿童用药
            this.addForm.medication_for_pregnancy_x_lactation = data.medication_for_pregnancy_x_lactation;//妊娠与哺乳用药
            this.addForm.medication_for_aged = data.medication_for_aged;//老年人用药
            this.addForm.properties = data.properties;//性状
            this.addForm.packing = data.packing;//包装
            this.addForm.dosage_form = data.dosage_form;//剂型
            this.addForm.storage = data.storage;//贮藏
            this.addForm.pharmacological_action = data.pharmacological_action;//药理作用
            this.addForm.expiry_date = data.expiry_date;//有效期
            this.addForm.detail = data.detail;
            this.addForm.sort= data.sort;


            this.skuList = data.sku_list
            for(let i=0;i<this.skuList.length;i++){
              this.specArr.push(this.skuList[i].id)
              this.specArrTemp.push(this.skuList[i].id)
              this.specValueArr.push(this.skuList[i])
              this.specValueArrAAAA.push([])
              /*if(this.skuList[i].id == this.specArr[this.specArr.length - 1]){
                this.specValueArr.push(this.skuList[i])
                this.specValueArrAAAA.push([])
                break;
              }*/
            }
            //sku操作
            /*data.sku_list.forEach((item,index) => {
              this.specArr.push(item.id)
              this.specArrTemp.push(item.id)
              for(let i=0;i<this.skuList.length;i++){
                if(this.skuList[i].id == item.id){
                  this.specValueArr.push(this.skuList[i])
                  break;
                }
              }
              let sku_value = []
              item.sku_value_list.forEach((item2,index2) => {
                sku_value.push(item2.id)
              })
              this.specValueArrAAAA.push(sku_value)
            })*/
            /*this.addSkuBtn(2,data.goods_sku_table);*/
            /*console.log(this.specArr)
            console.log(this.specValueArr)
            console.log(this.specValueArrAAAA)*/
            this.$message({
              message: '获取成功',
              type: 'success'
            });

            if(this.formStoreOne&&this.addForm.merchant_id){
              this.selectGoodsExists()
            }

          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          /*loadingOne.close()*/
        },

        upcChange() {
          console.log('upcChange')
          //防止第一次进来的时候选择upc码时会执行两次getSystemMedicineByUpc方法
          /*if(!this.upcFistGetFlag){
            return
          }*/
          let flag = false;
          for(let i=0;i<this.upcList.length;i++){
            if(this.upcList[i].value==this.addForm.upc){
              flag = true
              break;
            }
          }
          if(!flag){
            console.log('匹配失败')
            console.log(this.upcFistGetFlag)
            this.upcFistGetFlag = true;
            this.upcMatchFlag = true;
            /*this.addForm.id = data.id;*/
            /*this.addForm.upc = data.upc;*/
            this.addForm.name = ''

            this.addForm.sku_ssn = ''
            this.addForm.approval_number = ''
            this.addForm.specification = ''

            this.addForm.thumb_id = []
            this.fileList = []
            this.picList = []

            this.addForm.selling_price =''
            this.addForm.stock = ''
            this.addForm.manufacturer = ''
            this.addForm.manufacturer_address = ''
            this.addForm.manufacturer_contact = ''
            this.addForm.electronic_regulatory_code = ''
            this.addForm.usage_and_dosage = ''
            this.addForm.indications = ''
            this.addForm.adapt_to_the_crowd = ''
            this.addForm.precautions = ''
            this.addForm.component = ''
            this.addForm.adverse_reactions = ''
            this.addForm.contraindications = ''
            this.addForm.recautions = ''
            this.addForm.interaction = ''
            this.addForm.medication_for_children = ''
            this.addForm.medication_for_pregnancy_x_lactation = ''
            this.addForm.medication_for_aged = ''
            this.addForm.properties = ''
            this.addForm.packing = ''
            this.addForm.dosage_form = ''
            this.addForm.storage = ''
            this.addForm.pharmacological_action = ''
            this.addForm.expiry_date = ''
            this.addForm.detail = ''
            this.addForm.sort= ''


            this.skuList = []
            this.specArr = []
            this.specArrTemp = []
            this.specValueArr = []
            this.specValueArrAAAA = []
          } else{
            this.getSystemMedicineByUpc(this.addForm.upc)
          }
        },


        //选择门店
        chooseMerchantByAdd(id,status) {
          this.addForm.classify_first_id = '';
          this.addForm.classify_second_id = '';
          this.addForm.classify_id = '';
          this.classifyList = [];
          this.classifyListSecond = [];
          this.getGoodsClassifyList(id)
          if(id){
            //判断商品列表中是否存在该upc
            this.selectGoodsExists()
          }
        },

        //获取门店的分类
        async getGoodsClassifyList(id,pid){
          if(!id){
            this.classifyList = []
            return ;
          }
          this.page = this.page
          let params = {
            limit:99,
            page:1,
            merchant_id: id,
            pid: pid
          }
          const res = await this.$api.getGoodsClassifyList(params);
          if(res.data.level=='success'){
            let list = res.data.data;
            if(pid){
              this.classifyListSecond = list;
            } else{
              this.classifyList = list;
            }
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        //获取商品规格
        async getGoodsSkuList(){
          const res = await this.$api.getGoodsSkuList({page: 1,limit: 999});
          if(res.data.level=='success'){
            this.skuList = res.data.data
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        //获取促销规则
        async getDiscountSalesRule(){
          const res = await this.$api.getDiscountSalesRule({page: 1,limit: 999});
          if(res.data.level=='success'){
            this.discountSalesRuleList = res.data.data
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        chooseClassifyByAdd(type) {
          if(type=="first"){
            this.getGoodsClassifyList(this.addForm.merchant_id,this.addForm.classify_first_id)
            this.addForm.classify_id = [];
            this.addForm.classify_second_id = '';
            this.addForm.classify_id.push(this.addForm.classify_first_id)
          } else if(type == "second"){
            this.addForm.classify_id.push(this.addForm.classify_second_id)
          }
        },

        //选择规格
        chooseSpec() {//specValueArr
          /*console.log(this.specArr)*/
          /*this.specValueArrAAAA = []
          this.specValueArr = []
          this.specArr.forEach((item1,index1) => {
            this.skuList.forEach((item2,index2) => {
              if(item1 == item2.id){
                this.specValueArr.push(item2)
              }
            })

            this.specValueArrAAAA.push([])
          })*/
          /*console.log(this.specValueArr)*/
          //添加规格
          if(this.specArrTemp.length<this.specArr.length){
            for(let i=0;i<this.skuList.length;i++){
              if(this.skuList[i].id == this.specArr[this.specArr.length - 1]){
                this.specValueArr.push(this.skuList[i])
                break;
              }
            }
            this.specValueArrAAAA.push([])
          } else {//移除规格
            for(let i=0;i<this.specArrTemp.length;i++){
              let flag = true;
              for(let j=0;j<this.specArr.length;j++){
                if(this.specArrTemp[i]==this.specArr[j]){
                  flag = false;
                }
              }
              if(flag){
                for(let k=0;k<this.specValueArr.length;k++){
                  if(this.specValueArr[k].id==this.specArrTemp[i]){
                    this.specValueArr.splice(k,1)
                    this.specValueArrAAAA.splice(k,1)
                    break;
                  }
                }
                break;
              }
            }
          }
          /*console.log(this.specValueArr)
          console.log(this.specValueArrAAAA)*/
          this.specArrTemp = this.specArr
        },

        //添加规格和规格值
        addSkuBtn() {
          /*console.log(this.specArr)//选择的规格
          console.log(this.specValueArrAAAA)//选择的规格值*/
          let isHaveNull = false
          this.specValueArrAAAA.forEach((item,index) => {
            console.log(item)
            if(item.length==0){
              isHaveNull = true
            }
          })
          if(isHaveNull){
            this.$message({
              message: '请选择规格值',
              type: 'error',
            });
            return
          }
          let allArr =this.cartesianProductOf(...this.specValueArrAAAA)//组合的sku

          let specNameArr = [] //规格名称

          this.specArr.forEach((item,index) => {
            this.skuList.forEach((item2,index2) => {
              if(item == item2.id){
                specNameArr.push({id: item,name: item2.name})
              }
            })
          })
          /*console.log(specNameArr)*/

          let tableData = []

          allArr.forEach((item1,index1) => {
            let specArr = []
            this.specArr.forEach((item2,index2) => {
              this.skuList.forEach((item3,index3) => {
                if(item2==item3.id){
                  item3.value_list.forEach((item4,index4) => {
                    if(item4.id==item1[index2]){
                      specArr.push({pid: item3.id,name: item4.value,id: item4.id})
                    }
                  })
                }
              })
            })
            tableData.push({skuArr: specArr,other: {thumb_id: '',thumb_url: '',price: '',stock: '',code: ''}})
          })

          this.skuTableData = tableData
          this.specNameArr = specNameArr
          /*console.log(tableData)*/
          this.addSpuVisible = false
        },

        //sku变体组合算法
        cartesianProductOf() {
          return Array.prototype.reduce.call(arguments,function(a, b) {
            var ret = [];
            a.forEach(function(a) {
              b.forEach(function(b) {
                ret.push(a.concat([b]));
              });
            });
            return ret;
          }, [[]]);
        },

        showAddSkuDialog() {
          this.addSpuVisible = true;
        },

        async selectGoodsExists() {
          const res = await this.$api.selectGoodsExists({upc: this.addForm.upc,merchant_id: this.addForm.merchant_id});
          if(res.data.level=='success'){
            if(res.data.data==1){
              this.$alert('该门店的商品列表中已经有与该UPC码匹配的商品了', '提示', {
                confirmButtonText: '我知道了',
                callback: action => {

                }
              });
            }
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },

        //新增提交按钮
        async addSubmitBtn(){

          //添加规格参数
          /*console.log(this.specArr)
          console.log(this.specValueArrAAAA)

          let sku_value_arr = []
          let sku_info_arr = []

          this.specArr.forEach((item,index) => {
            let skuObj = {}
            skuObj.sku_id = item
            skuObj.sku_value_id = this.specValueArrAAAA[index]
            /!*skuObj[item] = this.specValueArrAAAA[index]*!/
            sku_value_arr.push(skuObj)
          })

          this.skuTableData.forEach((item,index) => {
            let skuArr = []
            let tempArr = []
            item.skuArr.forEach((item,index) => {
              let tempObj = {}
              tempObj[item.pid] = item.id
              skuArr.push(tempObj)
            })
            tempArr.push(skuArr)
            tempArr.push(item.other.thumb_id)
            tempArr.push(item.other.price)
            tempArr.push(item.other.stock)
            tempArr.push(item.other.code)
            sku_info_arr.push(tempArr)
          })

          console.log(sku_value_arr)
          console.log(sku_info_arr)

          this.addForm.sku_value_arr = sku_value_arr
          this.addForm.sku_info_arr = sku_info_arr*/

          //设置图片ID
          this.addForm.thumb_id = this.picList.map((item,index) => {
            return item.id
          })

          const params = this.addForm;
          const res = await this.$api.setGoods(params);
          if(res.data.level=='success'){
            this.$message({
              message: '添加成功',
              type: 'success',
            });
            this.$router.back(-1)
          }else{
            this.$message({
              message: res.data.message,
              type: 'warning'
            });
          }
        },


        //上传sku图片
        skuUploadSuccess(res, file,index) {
          this.skuTableData[index].other.thumb_id = res.data.id
          this.skuTableData[index].other.thumb_url = res.data.img_url
        },

        //上传sku图片之前
        beforeSkuAvatarUpload(index) {
          /*console.log(index)
          console.log('nihao')*/
        },

        /*submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              alert('submit!');
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        resetForm(formName) {
          this.$refs[formName].resetFields();
        },*/


        handleSuccess(res, file){
          this.picList.push({id: res.data.id,key: file.uid,url: res.data.img_url})
        },
        //上传失败提示
        uploadError() {
          this.$message.error("上传失败，请重新上传");
        },
        updateFile(val) {
          this.picList = val
        },

        /**
         * 清空上传组件
         */
        emptyUpload() {
          const mainImg = this.$refs.upload
          if (mainImg) {
            if (mainImg.length) {
              mainImg.forEach(item => {
                item.clearFiles()
              })
            } else {
              this.$refs.upload.clearFiles()
            }
          }
        },

        back() {

        }

      }
    }
</script>

<style scoped>
  .action-bar{
    background-color: #ffffff;
    height: 60px;
    margin: 10px 0px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 20px;
  }
  .add-goods{
    padding: 10px 0px;
    border-left: 15px solid #EDF1F5;
    border-right: 15px solid #EDF1F5;
    border-top: 15px solid #EDF1F5;
  }

  .step-title{
    position: fixed;
    background-color: #ffffff;
    z-index: 999;
    height: 50px;
    border: 1px solid red;
    top: 0 !important;
    z-index: 999999999999;
  }
  /*.step-title h1{
    font-size: 17px;
    color: #414658;
    padding: 20px 0 20px 20px;
  }*/

  .divider{
    width: 100%;
    height: 15px;
    background-color: #EDF1F5;
  }

  .isFixed{
    position: fixed;
    top: 0;
    left: 300px;
    z-index: 99999;
  }

  .add-goods .step{
  }
  .add-goods .step h1{
    font-size: 17px;
    color: #414658;
    border-bottom: 1px solid #EDEDED;
    padding: 20px 0 20px 20px;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #807979;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .spec-item{
    padding-bottom: 30px;
  }
  .spec-item:first-child{
    padding-bottom: 0;
  }

  table.gridtable {
    font-family: verdana,arial,sans-serif;
    font-size:11px;
    color:#333333;
    border-width: 1px;
    border-color: #666666;
    border-collapse: collapse;
    margin-left: 50px;
    margin-bottom: 20px;
  }
  table.gridtable th {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #dedede;
  }
  table.gridtable td {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #ffffff;
  }

</style>
